<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/9/29
 * Time: 15:37
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Order extends Base
{
    /**
     * 订单数据-
     */
    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            $map['is_delete'] = 0;
            $map['order_contract'] = ['<>',3];
            if(isset($n_title)&&$n_title!="")
            {
                $map['order_no|name|mobile|express_no'] = ['like',"%" . $n_title . "%"];
            }
            if(isset($contract)&&$contract!="")
            {
                $map['order_contract'] = $contract;
            }
            if(isset($orderid)&&$orderid!="")
            {
                $map['order_id'] = $orderid;
            }
            if(isset($type) && $type){
                if($type == 1){
                    $map['is_pay'] = 0;
                }else{
                    $map['is_pay'] = 1;
                    if($type == 2){
                        $map['is_send'] = 0;
                    }
                    if($type == 3){
                        $map['is_send'] = 1;
                    }
                    if($type == 4){
                        $map['is_send'] = 2;
                    }
                    if($type == 5){
                        $map['is_send'] = 3;
                    }
                }
            }
            if(isset($oldnew)&&$oldnew!="")
            {
                $map['new_old'] = $oldnew;
            }
            if(isset($schoolid) && $schoolid != ''){
                $map['s.school_erp'] = $schoolid;
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end=="")
            {
                $map['pay_time'] = ['>= time',$start];
            }
            if(isset($end)&&$end!=""&&isset($start)&&$start=="")
            {
                $map['pay_time'] = ['<= time',$end];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end!="")
            {
                $map['pay_time'] = ['between time',[$start,$end]];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'o.*,user_username,user_phone,school_erp,school_name';
            $count = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->where($map)
                ->order('is_pay ASC,is_send ASC,created_at ASC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            //----------------------------------------------------------
            $allmoney = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
                ->join('up_school s','us.uson_school=s.school_id','LEFT')
                ->where($map)
                ->sum('total_price');
            $oids = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
                ->join('up_school s','us.uson_school=s.school_id','LEFT')
                ->where($map)
                ->column('order_id');
            $allnums = Db::table('up_self_order_detail')
                ->where('order_id','in',$oids)
                ->sum('num');// 获取总条数
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists, 'allmoney' => $allmoney, 'allnums' => $allnums]);
        }
        $schools = Db::table('up_school')
            ->where('school_id','>',0)
            ->field('school_erp,school_name')
            ->select();
        $this->assign('schools',$schools);
        return $this->fetch('order/index');
    }

    /**
     * 修改收货地址
     */
    public function orderUpdateAddress(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $param  = [
                'name'=>$name,
                'mobile'=>$mobile,
                'address'=>$address,
                'updated_at'=>date('Y-m-d H:i:s'),
            ];
            $res = Db::table('up_self_order')
                ->where('order_id',$order_id)
                ->update($param);
            if($res){
                return json(['code'=>200,'msg'=>'修改成功']);
            }else{
                return json(['code'=>100,'msg'=>'修改失败']);
            }
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        return $this->fetch('order/orderupdateaddress',['data'=>$order]);
    }
    /**
     * 订单发货
     */
    public function orderSend(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            if(empty($fahuo)){
                return json(['code'=>100,'msg'=>'选择不能为空']);
            }
            Db::startTrans();
            try{
            if($type == 1){
               $old_count = Db::table('up_self_order_detail')
                    ->where('order_id',$order_id)
                    ->where('detail_express_no','<>','')
                    ->count();
                $now_count = count($fahuo);
                $all_count = Db::table('up_self_order_detail')
                    ->where('order_id',$order_id)
                    ->count();
                if(($old_count+$now_count) >= $all_count){
                    Db::table('up_self_order')
                        ->where('order_id',$order_id)
                        ->update([
                            'is_send' => 1,
                            'send_time' => date('Y-m-d H:i:s')
                        ]);
                }
            }
            $param  = [
                'detail_express'=>$express,
                'detail_express_no'=>$express_no,
                'updated_at'=>date('Y-m-d H:i:s'),
            ];
            $deids = implode($fahuo,',');
            Db::table('up_self_order_detail')
                ->where('detail_id','in',$deids)
                ->update($param);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
        }
        $field = 'num,unit_price,goods_info,good_id,good_name,detail_id,detail_express,detail_express_no';
        $details = Db::table('up_self_order_detail')->alias('od')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where('order_id',$order_id)
            ->field($field)
            ->select();
        return $this->fetch('order/ordersend',['type'=>$type,'data'=>$order,'details'=>$details]);
    }

    /**
     * 取消订单
     * @return \think\response\Json
     */
    public function orderCancle(){
        $order_id = input('id');
        $is_pay = Db::table('up_self_order')->where('order_id', $order_id)->value('is_pay');
        if($is_pay != 0){
            return json(['code' => 100, 'msg' => '只有未支付订单才可以关闭']);
        }
        Db::startTrans();
        try{
            $field = 'goods_id,num,attr_id';
            $details = Db::table('up_self_order_detail')
                ->where('order_id',$order_id)
                ->field($field)
                ->select();
//
            $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
//
            foreach ($details as $k=>$v){
                if($contract == 1){
                    //1、加上商品的库存
                    Db::table('up_self_goods')->where('good_id',$v['goods_id'])->setInc('good_stock',$v['num']);
                    //2、加上attr的库存
                    Db::table('up_self_goods_attr')->where('attr_id',$v['attr_id'])->setInc('stock',$v['num']);
                }else{
                    //1、加上商品的库存
                    Db::table('up_goods')->where('good_id',$v['goods_id'])->setInc('good_stock',$v['num']);
                    //2、加上attr的库存
                    Db::table('up_goods')->where('good_id',$v['goods_id'])->setInc("good_{$v['attr_id']}",$v['num']);
                }

            }
            //3、改变订单状态
            Db::table('up_self_order')->where('order_id',$order_id)->setField('is_pay',2);
            Db::commit();
            return json(['code' => 200, 'msg' => '关闭成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 100, 'msg' => '关闭失败']);
        }
    }
    /**
     * 删除订单
     * @return \think\response\Json
     */
    public function orderDel(){
        $order_id = input('id');
        $can = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('is_pay,order_cancel_pay')
            ->find();
        if($can['is_pay'] == 2 && $can['order_cancel_pay'] == 2){
            return json(['code' => 100, 'msg' => '此订单还未退款，不可删除']);
        }
        $res = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->setField('is_delete',1);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }



    /**
     * 订单详情
     */
    public function orderInfo(){
        $order_id = input('order_id');
        $field = 'o.*,user_username,user_phone';
        $order = Db::table('up_self_order')->alias('o')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->where('order_id',$order_id)
            ->field($field)
            ->find();
        $where = [
            'order_id' => $order_id
        ];
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
        }
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id,good_coding';
        $details = Db::table('up_self_order_detail')->alias('od')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
        return $this->fetch('order/orderinfo',['data'=>$order,'goods'=>$details]);
    }
    /**
     * 查看评价
     * @return mixed|\think\response\Json
     */
    public function orderComments(){
        if(request()->isAjax()){
            extract(input());
            $order_id = input('order_id');
            $contract = input('contract');
            $good_table = 'up_self_goods';
            $goods_comment_table = 'up_self_goods_comment';
            if($contract != 1){
                $good_table = 'up_goods';
                $goods_comment_table = 'up_goods_comment';
            }
            //
            $where = [
                'comment_order_id' => $order_id
            ];
            $count = Db::table($goods_comment_table)->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join("$good_table g",'a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table($goods_comment_table)->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join("$good_table g",'a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->field('a.*,uuu.user_username,uuu.user_phone,good_name')
                ->select();
            if($lists){
                foreach ($lists as $k=>$v){
                    if($v['comment_image']){
                        $lists[$k]['comment_image'] = explode(',',$v['comment_image']);
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $order_id = input('order_id');
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $this->assign('order_id',$order_id);
        $this->assign('contract',$contract);
        return $this->fetch('order/ordercomments');
    }
    /**
     * 查看物流列表
     * @return mixed|\think\response\Json
     */
    public function orderWuliu(){
        if(request()->isAjax()){
            extract(input());
            $order_id = input('order_id');
            //
            $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
            $good_table = 'up_self_goods';
            if($contract != 1){
                $good_table = 'up_goods';
            }
            $count = Db::table('up_self_order_detail')->alias('od')
                ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                ->where('order_id',$order_id)
                ->count();// 获取总条数
            $field = 'num,unit_price,goods_info,good_id,good_name,detail_id,detail_express,detail_express_no';
            $lists = Db::table('up_self_order_detail')->alias('od')
                ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                ->where('order_id',$order_id)
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $order_id = input('order_id');
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $this->assign('order_id',$order_id);
        $this->assign('contract',$contract);
        return $this->fetch('order/wuliu');
    }
    /**
     * 查看物流详情
     * @return mixed|\think\response\Json
     */
    public function wuliuInfo(){
        $code = input('express_no');
        $info = orderWuLiu($code);
//        dump($info);
        $this->assign('info',$info);
        return $this->fetch('order/wuliuinfo');
    }
    /**
     * 查看发票
     * @return mixed|\think\response\Json
     */
    public function fapiao(){
        $order_id = input('order_id');
        $info = Db::table('up_self_order')->where('order_id', $order_id)->find();
        $this->assign('info',$info);
        return $this->fetch('order/fapiao');
    }

    //导出
    public function excelOutOrder()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['is_delete'] = 0;
        $map['order_contract'] = ['<>',3];
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|name|mobile|express_no'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($contract)&&$contract!="")
        {
            $map['order_contract'] = $contract;
        }
        if(isset($orderid)&&$orderid!="")
        {
            $map['order_id'] = $orderid;
        }
        if(isset($type) && $type){
            if($type == 1){
                $map['is_pay'] = 0;
            }else{
                $map['is_pay'] = 1;
                if($type == 2){
                    $map['is_send'] = 0;
                }
                if($type == 3){
                    $map['is_send'] = 1;
                }
                if($type == 4){
                    $map['is_send'] = 2;
                }
                if($type == 5){
                    $map['is_send'] = 3;
                }
            }
        }
        if(isset($oldnew)&&$oldnew!="")
        {
            $map['new_old'] = $oldnew;
        }
        if(isset($schoolid) && $schoolid != ''){
            $map['s.school_erp'] = $schoolid;
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end=="")
        {
            $map['pay_time'] = ['>= time',$start];
        }
        if(isset($end)&&$end!=""&&isset($start)&&$start=="")
        {
            $map['pay_time'] = ['<= time',$end];
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end!="")
        {
            $map['pay_time'] = ['between time',[$start,$end]];
        }
        $field = [
            'order_no','order_back_order_id','total_price','express_original_price','all_goods_price',
            'all_good_nums','name','mobile','address','remark',
            'created_at','is_pay','pay_type','pay_time','school_name',
            'is_send','send_time','express','express_no','order_contract',
            'order_cancel_status','order_cancel_pay','order_cancel_money','order_erp_year','order_erp_done',
            'new_old'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->where($map)
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '订单号', '第三方支付平台订单号', '总价（含邮费）', '运费', '衣服总价',
                '衣服总数量', '收件人', '收件电话', '收件地址', '备注',
                '创建订单时间', '是否支付', '支付平台', '支付时间', '学校名字',
                '是否发货', '发货时间', '发货物流', '物流单号', '订单类型',
                '订单是否取消', '是否已退款（取消了订单的才有）', '退款金额（取消了订单的才有）', '年份', '交期',
                '新老订单'
            ];
            $status = ['is_pay','pay_type','is_send','order_contract','order_cancel_status','order_cancel_pay','new_old'];
            $values = [
                 'is_pay' => [0 => '待支付',1 => '已支付',2 => '已取消']
                ,'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
                ,'order_contract' => [1 => '自营订单',2 => '增补订单']
                ,'order_cancel_status' => [1 => '未取消',2 => '取消被拒',3 => '已同意取消',4 => '待审核']
                ,'order_cancel_pay' => [1 => '正常',2 => '未打款',3 => '已打款']
                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
            ];
            $res = exportExcel('order',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    //导出
    public function excelOutDetail()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['order_contract'] = ['<>',3];
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|name|mobile|express_no'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($contract)&&$contract!="")
        {
            $map['order_contract'] = $contract;
        }
        if(isset($orderid)&&$orderid!="")
        {
            $map['order_id'] = $orderid;
        }
        if(isset($type) && $type){
            if($type == 1){
                $map['is_pay'] = 0;
            }else{
                $map['is_pay'] = 1;
                if($type == 2){
                    $map['is_send'] = 0;
                }
                if($type == 3){
                    $map['is_send'] = 1;
                }
                if($type == 4){
                    $map['is_send'] = 2;
                }
                if($type == 5){
                    $map['is_send'] = 3;
                }
            }
        }
        if(isset($oldnew)&&$oldnew!="")
        {
            $map['new_old'] = $oldnew;
        }
        if(isset($schoolid) && $schoolid != ''){
            $map['s.school_erp'] = $schoolid;
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end=="")
        {
            $map['pay_time'] = ['>= time',$start];
        }
        if(isset($end)&&$end!=""&&isset($start)&&$start=="")
        {
            $map['pay_time'] = ['<= time',$end];
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end!="")
        {
            $map['pay_time'] = ['between time',[$start,$end]];
        }
        $field = [
            'o.order_no','unit_price','num','attr_id','goods_info',
            'goods_coding_unique','name','mobile','address','remark',
            'o.created_at','is_pay','pay_type','pay_time','school_name',
            'is_send','send_time','express','express_no','order_contract',
            'order_cancel_status','order_cancel_pay','order_cancel_money','od.pay_year','order_erp_done',
            'o.new_old','od.th_status'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_self_order_detail od','o.order_id=od.order_id','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->where($map)
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '订单号', '单价', '数量', '尺码', '产品信息',
                '唯一条码', '收件人', '收件电话', '收件地址', '备注',
                '创建订单时间', '是否支付', '支付平台', '支付时间', '学校名字',
                '是否发货', '发货时间', '发货物流', '物流单号', '订单类型',
                '订单是否取消', '是否已退款（取消了订单的才有）', '退款金额（取消了订单的才有）', '年份', '交期',
                '新老订单','是否售后（只针对此条明细）'
            ];
            $status = ['is_pay','pay_type','is_send','order_contract','order_cancel_status','order_cancel_pay','new_old','th_status'];
            $values = [
                 'is_pay' => [0 => '待支付',1 => '已支付',2 => '已取消']
                ,'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
                ,'order_contract' => [1 => '自营订单',2 => '增补订单']
                ,'order_cancel_status' => [1 => '未取消',2 => '取消被拒',3 => '已同意取消',4 => '待审核']
                ,'order_cancel_pay' => [1 => '正常',2 => '未打款',3 => '已打款']
                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
                ,'th_status' => [0 => '无售后',1 => '换货',2 => '退货']
            ];
            $res = exportExcel('orderinfo',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}